package messageHandler;

import java.util.StringTokenizer;

import org.apache.log4j.Logger;
import config.ConfigData;
import types.Keyword;
import types.Member;
import types.TextMessage;

public class MessageHandler
{
    // Logger
    private static Logger myLogger = Logger.getLogger(MessageHandler.class.getName());
    
    /**
     * Starts thread to handle message processing
     * @param tm
     */
    public static void handleTextMessage(TextMessage tm)
    {
	myLogger.info("Creating thread for processing of text message: " + tm);
	
	// Make new thread
	Thread thread = new Thread(getRunnable(tm),tm.getFromPhone());
	
	// start thread to do the work
	myLogger.info("Starting thread for processing of text message: " + tm);
	thread.start();
    }
    
    /**
     * The tasks that will be performed for new text messages
     * @return
     */
    private static Runnable getRunnable(final TextMessage tm)
    {
	Runnable  r = new Runnable()
	{
	   public void run()
	   {
	       // Save text message into the database
	       tm.keep();
	       
	       // process it
	       processMessageParts(tm);
	   }
	};
	
	return r;
    }
    
    /**
     * Logic to process message parts and the keywords
     * 
     * @param tm
     */
    private static void processMessageParts(TextMessage tm)
    {	
	// Parse message
	StringTokenizer tokens = new StringTokenizer(tm.getMessageContents());
	
	// Handle special keywords
	if (false == tokens.hasMoreElements())
	{
	    myLogger.info("Text message had no content. Cannot process: " + tm);
	}
	else
	{
	    String keyword = tokens.nextToken();
	    keyword=keyword.toLowerCase(); // standardize input
	    
	    // Switch on the keyword
	    switch(keyword){
		case "register": keyword_register(tm, tokens); break;
		case "new": keyword_new(keyword,tm,tokens); break;
		default: keyword_keyword(tm,tokens); break;
	    }
	    
	}
    }

    /**
     * Handles text messages with a keyword of <keyword>
     * 
     * @param tm
     * @param tokens
     */
    private static void keyword_new(String inKeyword, TextMessage tm, StringTokenizer tokens)
    {
	myLogger.info("Processing text message with keyword of 'new': " + tm);	
	
	String keywordToken = null;
	
	if(tokens.hasMoreTokens())
	{
	    keywordToken = tokens.nextToken();
	}
	else
	{
	    myLogger.warn("Received a text message with keyword of 'new' but no keyword.");
	    return; // exit
	}
	
	// Insert into database
	Keyword keyword = new Keyword(keywordToken);
	keyword.keep();
	
    }

    /**
     * Handles text messages with a keyword of "new"
     * 
     * @param tm
     * @param tokens
     */
    private static void keyword_keyword(TextMessage tm, StringTokenizer tokens)
    {
	myLogger.info("Processing text message with keyword of <keyword>: " + tm);
	
	// Nothing now. Already added to the database.
    }
    
    /**
     * Handles text messages with a keyword of "register"
     * 
     * @param tm
     * @param tokens
     */
    private static void keyword_register(TextMessage tm, StringTokenizer tokens)
    {
	myLogger.info("Processing text message with keyword of 'register': " + tm);
	
	// Initialize
	String firstName="";
	String lastName="";
	String email="";
	
	// Get parts from the message	
	if(tokens.hasMoreTokens())
	{
	    firstName = tokens.nextToken();
	}
	else
	{
	    myLogger.warn("Received a text message with keyword of 'register' but no first name.");
	    return; // exit
	}
	if(tokens.hasMoreTokens())
	{
	    lastName = tokens.nextToken();
	}
	else
	{
	    myLogger.warn("Received a text message with keyword of 'register' but no last name.");
	    return; // exit
	}
	if(tokens.hasMoreTokens())
	{
	    email = tokens.nextToken();
	}
	else
	{
	    // Email is optional.
	}
	
	// Perform clean up of input
	firstName=firstName.toLowerCase();
	lastName=lastName.toLowerCase();
	email=email.toLowerCase();
	
	// Create a member
	Member member = new Member(tm.getFromPhone(),firstName,lastName,email);
	myLogger.info("Created member: " + member);
	
	// Add to the database
	member.keep();
	
	// Complete ?
    }
}
